package org.ofbiz.wvtools.email;

import java.io.File;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.ofbiz.base.util.Debug;
import org.ofbiz.base.util.UtilDateTime;
import org.ofbiz.base.util.UtilMisc;
import org.ofbiz.base.util.UtilValidate;
import org.ofbiz.entity.Delegator;
import org.ofbiz.entity.GenericEntityException;
import org.ofbiz.entity.GenericValue;
import org.ofbiz.entity.util.EntityUtil;
import org.ofbiz.service.DispatchContext;
import org.ofbiz.service.GenericServiceException;
import org.ofbiz.service.LocalDispatcher;
import org.ofbiz.service.ServiceUtil;

import com.spire.doc.Document;
import com.spire.doc.FileFormat;

import javolution.util.FastMap;

public class BizEmailServices {
    public static final String module = BizEmailServices.class.getName();
    public static final String resource = "WvtoolsUiLabels";

    public static String OFBIZ_HOME = System.getProperty("ofbiz.home") + "/hot-deploy/sys/webapp/sys";

    public static Map getOfferEmailTemplate(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess("createPersonFormEmail.success");
	Delegator delegator = dctx.getDelegator();
	String receiveUserName = (String) context.get("receiveUserName"); // 应聘者姓名
	String replaceUserName = "#userName#";
	try {
	    String baseId = "EIM_HRM_OFFER";
	    GenericValue temp = delegator.findOne("OfcEmailTemplate", UtilMisc.toMap("baseId", baseId), false);
	    if (UtilValidate.isEmpty(temp)) {
		return result;
	    }
	    String content = temp.getString("content");
	    content = content.replaceAll(replaceUserName, receiveUserName);

	    result.put("content", content);

	} catch (GenericEntityException e) {
	    Debug.logError(e, e.getMessage(), module);

	}
	return result;
    }

    /**
     * 按邮件模板发送Offer邮件
     * 
     * @param dctx
     * @param context
     * @return
     */
    public static Map sendOfferEmailByEmailAndUserName(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess("createPersonFormEmail.success");
	Delegator delegator = dctx.getDelegator();
	LocalDispatcher dispatcher = dctx.getDispatcher();
	GenericValue userLogin = (GenericValue) context.get("userLogin");

	String email = (String) context.get("email");
	String receiveUserName = (String) context.get("receiveUserName"); // 应聘者姓名
	String userLoginId = (String) context.get("userLoginId"); // 可选: 指定用户名

	if (UtilValidate.isEmpty(email)) {
	    result = ServiceUtil.returnError("sendEmailFromTemplate.error.email.isnull");
	    return result;
	}
	if (UtilValidate.isEmpty(userLoginId)) {
	    userLoginId = userLogin.getString("userLoginId");
	}

	String replaceUserName = "#userName#";

	try {
	    String baseId = "EIM_HRM_OFFER";
	    GenericValue temp = delegator.findOne("OfcEmailTemplate", UtilMisc.toMap("baseId", baseId), false);
	    if (UtilValidate.isEmpty(temp)) {
		return result;
	    }
	    String sendUserName = temp.getString("sendUserName");
	    String title = temp.getString("title");
	    String content = temp.getString("content");

	    // 保存历史
	    GenericValue gv = delegator.makeValue("EmailHistory",
		    UtilMisc.toMap("baseId", delegator.getNextSeqId("EmailHistory"), "enabled", "Y", "historyTypeId",
			    baseId, "userLoginId", userLoginId, "memberEmail", email, "receiveUserName", email));

	    // 处理发送邮件: 替换 链接
	    if (UtilValidate.isNotEmpty(receiveUserName)) {

		gv.set("receiveUserName", receiveUserName);
		content = content.replaceAll(replaceUserName, receiveUserName);
	    }
	    gv.set("sendUserName", sendUserName);
	    gv.set("title", title);
	    gv.set("content", content);
	    gv.set("createByUserLoginId", userLoginId);
	    gv.set("emailTypeId", temp.getString("emailTypeId"));

	    Timestamp now = UtilDateTime.nowTimestamp();
	    gv.set("sendDate", now);
	    gv.create();

	    // 发邮件
	    if (UtilValidate.isEmpty(userLogin)) {
		userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", "system"), true);
	    }
	    dispatcher.runAsync("sendSingleEmailHtml", UtilMisc.toMap("userLogin", userLogin, "mailTo", email,
		    "personalName", sendUserName, "mailSubject", title, "mailBody", content));
	} catch (GenericEntityException e) {
	    Debug.logError(e, e.getMessage(), module);
	} catch (GenericServiceException e) {
	    Debug.logError(e, e.getMessage(), module);
	}
	return result;
    }

    /**
     * 按邮件模板发送Offer邮件
     * 
     * @param dctx
     * @param context
     * @return
     */
    public static Map sendOfferEmail(DispatchContext dctx, Map<String, ? extends Object> context) {
	Map<String, Object> result = ServiceUtil.returnSuccess("createPersonFormEmail.success");
	Delegator delegator = dctx.getDelegator();
	LocalDispatcher dispatcher = dctx.getDispatcher();
	GenericValue userLogin = (GenericValue) context.get("userLogin");
	String id = (String) context.get("id");
	String userLoginId = (String) context.get("userLoginId"); // 可选: 指定用户名
	try {
	    GenericValue hrOffer = delegator.findOne("HrOffer", UtilMisc.toMap("id", id), false);
	    String candidateId = hrOffer.getString("candidateId");
	    String company = hrOffer.getString("company"); 
	    if(UtilValidate.isEmpty(company))company = "OFFER_COM_TYPE0";
	    if (UtilValidate.isEmpty(candidateId)) {
		result = ServiceUtil.returnError("sendEmailFromTemplate.error.candidateId.isnull");
		return result;
	    }
	    GenericValue hrCandidateInfo = delegator.findOne("HrCandidateInfo", UtilMisc.toMap("id", candidateId),
		    false);
	    if (UtilValidate.isEmpty(candidateId)) {
		result = ServiceUtil.returnError("sendEmailFromTemplate.error.hrCandidateInfo.isnull");
		return result;
	    }
	    String email = hrCandidateInfo.getString("email"); // 邮箱地址
	    String receiveUserName = hrCandidateInfo.getString("name"); // 收件人姓名

	    if (UtilValidate.isEmpty(email)) {
		result = ServiceUtil.returnError("sendEmailFromTemplate.error.email.isnull");
		return result;
	    }
	    if (UtilValidate.isEmpty(userLoginId)) {
		userLoginId = userLogin.getString("userLoginId");
	    }

	    String toNameField1 = "#姓名#";
	    String toNameField2 = "#基薪#";
	    String toNameField3 = "#保障金#";
	    String toNameField4 = "#月薪#";
	    String toNameField5 = "#有效期#";
	    String toNameValue2 = hrOffer.getString("salaryBaseId");
	    String toNameValue3 = hrOffer.getString("salaryEnsureId");
	    String toNameValue4 = hrOffer.getString("monthlySalary");
	    String toNameValue5 = hrOffer.getString("expiryDate");
	    if(UtilValidate.isEmpty(toNameValue5))toNameValue5  = UtilDateTime.nowTimestamp().toString().substring(0,10);
	    Date date1 = new SimpleDateFormat("yyyy-MM-dd").parse(toNameValue5);
	    toNameValue5 = new SimpleDateFormat("yyyy年MM月dd日").format(date1);

	    
	    String path = OFBIZ_HOME + "/images/model/offer.docx";
	    String filePath = OFBIZ_HOME + "/images/pdf/";
	    Map<String, Object> replaceMap = FastMap.newInstance();
	    List<GenericValue> companyList = delegator.findByAnd("DataDictionary", UtilMisc.toMap("dictionaryTypeId", "OFFER_COM_TYPE","dictionaryCode",company), null, false);
	    String toNameValue6 = hrOffer.getTimestamp("arrivalTime").toString();
	    if(UtilValidate.isNotEmpty(toNameValue6))toNameValue6  = toNameValue6.substring(0,10);
		   
	    Date date = new SimpleDateFormat("yyyy-MM-dd").parse(toNameValue6);
	    String toNameValue61 = new SimpleDateFormat("yyyy-MM-dd").format(date);
	    replaceMap.put("日期", UtilDateTime.nowTimestamp().toString().substring(0, 10));
	    replaceMap.put("姓名", receiveUserName);
	    replaceMap.put("职位", hrOffer.getString("position"));
	    replaceMap.put("公司", companyList.get(0).getString("description"));
	    replaceMap.put("年薪", hrOffer.getString("annualSalary"));
	    replaceMap.put("月薪", toNameValue4);
	    replaceMap.put("报道日期", toNameValue61);
	    Document doc = new Document();
	    doc.loadFromFile(path);
	    if (UtilValidate.isNotEmpty(replaceMap)) {
		Iterator keys = replaceMap.keySet().iterator();
		while (keys.hasNext()) {
		    String key = (String) keys.next();
		    String value = (String) replaceMap.get(key);
		    doc.replace("{" + key + "}", value, false, true);
		}
	    }
	    File parentDir = new File(OFBIZ_HOME + filePath);
	    if (!parentDir.exists()) {
		parentDir.mkdirs();
	    }
	    // 保存pdf文件
	    doc.saveToFile(filePath + id + ".pdf", FileFormat.PDF);
	    String uploadPath = filePath + id + ".pdf";
	    
	    
	    String baseId = "EIM_HRM_OFFER";
	    GenericValue temp = delegator.findOne("OfcEmailTemplate", UtilMisc.toMap("baseId", baseId), false);
	    if (UtilValidate.isEmpty(temp)) {
		return result;
	    }
	    String sendUserName = temp.getString("sendUserName");
	    String title = temp.getString("title");
	    String content = temp.getString("content");

	    // 保存历史
	    GenericValue gv = delegator.makeValue("EmailHistory",
		    UtilMisc.toMap("baseId", delegator.getNextSeqId("EmailHistory"), "enabled", "Y", "historyTypeId",
			    baseId, "userLoginId", userLoginId, "memberEmail", email, "receiveUserName", email));

	    // 处理发送邮件: 替换 链接
	    if (UtilValidate.isNotEmpty(receiveUserName)) {
		gv.set("receiveUserName", receiveUserName);
		content = content.replaceAll(toNameField1, receiveUserName);
		content = content.replaceAll(toNameField2, toNameValue2);
		content = content.replaceAll(toNameField3, toNameValue3);
		content = content.replaceAll(toNameField4, toNameValue4);
		content = content.replaceAll(toNameField5, toNameValue5);
	    }
	    gv.set("sendUserName", sendUserName);
	    gv.set("title", title);
	    gv.set("content", content);
	    gv.set("createByUserLoginId", userLoginId);
	    gv.set("emailTypeId", temp.getString("emailTypeId"));

	    Timestamp now = UtilDateTime.nowTimestamp();
	    gv.set("sendDate", now);
	    gv.create();
	    // 发邮件
	    if (UtilValidate.isEmpty(userLogin)) {
		userLogin = delegator.findOne("UserLogin", UtilMisc.toMap("userLoginId", "system"), true);
	    }
	    dispatcher.runAsync("sendSingleEmailHtml", UtilMisc.toMap("userLogin", userLogin, "mailTo", email,
		    "personalName", sendUserName, "mailSubject", title, "mailBody", content, "uploadPath", uploadPath));
	    hrOffer.set("isSendMail", "Y");
	    hrOffer.store();
	} catch (GenericEntityException e) {
	    Debug.logError(e, e.getMessage(), module);
	} catch (GenericServiceException e) {
	    Debug.logError(e, e.getMessage(), module);
	} catch (ParseException e) {
	    Debug.logError(e, e.getMessage(), module);
	    e.printStackTrace();
	}
	return result;
    }

}